#include "Contacts.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

struct Contacts
{
    char *name;
    char *phone;
};

Conts *InitContacts()
{
    Conts *s = (Conts *)malloc(sizeof(Conts));
    s->name = NULL;
    s->phone = NULL;
    return s;
}



Conts *CreateConts()
{
    Conts *s = (Conts *)malloc(sizeof(Conts));
    if (s == NULL)
    {
        printf("Createelinfo malloc error!\n");
        exit(-1);
    }
    FILE* f = fopen("./通讯录.txt","a");
    if(f == NULL)
    {
        printf("文件打开失败\n");
        return NULL;
    }
    char name[15];
    printf("请输入用户姓名：\n");
    scanf("%s", name);
    fputs(name,f);
    fputc('\n',f);

    char phone[15];
    printf("请输入用户电话号码：\n");
    scanf("%s", phone);
    fputs(phone,f);
    fputc('\n',f);

    s->name = strdup(name); // 堆上的字符串
    s->phone = strdup(phone);
    fclose(f);
    return s;
}

Conts *GetConts(FILE* f)
{
    
    // FILE* f = fopen("./通讯录.txt","r");
    // if(f == NULL)
    // {
    //     printf("文件打开失败\n");
    //     return NULL;
    // }
    char p[15] = {0};
    Conts *s = (Conts *)malloc(sizeof(Conts));
    if (s == NULL)
    {
        printf("Createelinfo malloc error!\n");
        exit(-1);
    }
    char c;
    int i = 0;
    while(( c = fgetc(f) )!= EOF)
    {
        if(c == '\n')
        {
            p[i] = '\0';
            i = 0;
            break;
        }
        p[i++] = c;
    }
    s->name = strdup(p);
    while(( c = fgetc(f) )!= EOF)
    {
        if(c == '\n')
        {
            p[i] = '\0';
            i = 0;
            break;
        }
        p[i++] = c;
    }
    s->phone = strdup(p);
    //fclose(f);
    return s;
    
}

void SaveConts(void *p)
{
    FILE* f = fopen("./通讯录.txt","a");
    if(f == NULL)
    {
        printf("文件打开失败\n");
        return ;
    }
    Conts *s = (Conts *)p;
    fputs(s->name,f);
    fputc('\n',f);
    fputs(s->phone,f);
    fputc('\n',f);
    fclose(f);
}

void PrintConts(void *p)
{
    Conts *s = (Conts *)p;
    printf("姓名：%s  电话号码: %s\n", s->name, s->phone);
}

void ClearConts(void *p)
{
    Conts *s = (Conts *)p;
    free(s->name);
    free(s->phone);
    free(s);
}

bool IsEqual(void *p1, void *p2)
{
    Conts *s = (Conts *)p1;
    const char *value = (const char *)p2;
    return (strcmp(s->name, value) == 0 || strcmp(s->phone, value) == 0);
}

bool IsStr(void *p1, void *p2)
{
    Conts *s = (Conts *)p1;
    const char *value = (const char *)p2;
    char* p =  strstr(s->name, value) ;
    if(p != NULL)
    {
        return true;
    }
    return false;
}

int Namecmp(void *p1,void *p2)
{
    Conts *s1 = (Conts *)p1;
    Conts *s2 = (Conts *)p2;
    return strcmp(s1->name, s2->name) ;
}

int Namecmp2(void *p1,void *p2)
{
    Conts *s1 = (Conts *)p1;
    const char *value = (const char *)p2;
    return strcmp(s1->name, value) ;
}
